var util = require('../../utils/util.js')
var WxParse = require('../../wxParse/wxParse.js')
var qcloud = require('../../vendor/wafer2-client-sdk/index')
var app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    isHaveResume: null,
    submitText: '',
    submitdisabled: false,
    mode: true,
    animationData: {},
    height: '100%',
    positionInfo: {},
    similarPosiInfo: {},
    yingpinBtn: { text: '我要申请', disabled: false },
    successlabel: '',
    nonet: true,
    isHave: '',
    isExit: 0,
    canvasHeight: 0,
    canvasWidth: 0,
    rpx: 0,
    tempFilePath: '',
    imgUrl: '',
    imgHidden: false,
    wechatQrcode:'',
    click:false,
    background:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var positionId = options.pid
    var posiname = options.posiname
    var that = this
    util.post(app.api.isExitResume, { unionid: wx.getStorageSync('unionid') }, function (res) {
      that.setData({
        isHave: res.data,
      })
    })
    //加载分享海报二维码路径，之后画canvas海报
    util.request(app.api.wechatQrcode+`/${positionId}`, '', "GET").then((res)=>{
      that.setData({
        wechatQrcode: res.data,
      })
      that.getCanvas()
    }).catch((err)=>{
      console.log(err)
    })
    // util.request(app.api.getBackground, '', 'GET').then((res) => {
    //   that.setData({
    //     background: res.data,
    //   })
    //   console.log('background:'+that.background)
    // })
    util.post(app.api.getPositionDetail, { jobid: positionId }, function (res) {
      //获取职位详情
      that.setData({
        positionInfo: res.data,
      })
      // WxParse.wxParse('article', 'html', that.data.positionInfo.majorDuty, that, 5);
      //判断是否有资料
      if (app.globalData.openid != null) {
        util.post(app.api.getByUnionid, { unionid: app.globalData.unionid }, function (res) {
          if (res != null) {
            that.setData({
              isHaveResume: res,
            })
            wx.setStorageSync('isHaveResume', that.data.isHaveResume)
          }
        })
      }
      // if (that.data.isHaveResume=== null) {
      //   that.setData({
      //     submitText: "请先完善您的个人资料",
      //     isHaveResume: false
      //   });
      // } else {
      //   that.setData({
      //     submitText: "发送资料",
      //     isHaveResume: true
      //   });

      // }

      //判断是否已投递过
      try {
        var sendPosiArray = wx.getStorageSync('sendPosiArray')
        if (sendPosiArray) {
          // Do something with return value
          for (var i = 0; i < sendPosiArray.length; i++) {
            if (sendPosiArray[i] == app.globalData.positionDetail.id) {
              that.setData({
                submitText: '已申请',
                'yingpinBtn.disabled': true,
              })
            }
          }
        }
      } catch (e) {
        // Do something when catch error
      }
    })

    util.post(
      app.api.isExistRec,
      { unionid: app.globalData.unionid, jobid: positionId },
      function (res) {
        if (res.data == 'hasRec') {
          //已经应聘该职位
          that.setData({
            yingpinBtn: { text: '已申请', disabled: true },
          })
        } else if (res.data == 'notRec') {
          //未应聘该职位
          that.setData({
            yingpinBtn: { text: '我要申请', disabled: false },
          })
        } else {
          that.setData({
            isHaveResume: false,
          })
        }
      }
    )
  },

  //保存推送码
  saveFormIds: function () {
    var formIds = app.globalData.globalFormIds //获取globalFormIds
    if (formIds != null) {
      formIds = JSON.stringify(formIds)
      app.globalData.globalFormIds = ''
    }
    util.post(
      app.api.saveFormIds,
      { unionid: app.globalData.unionid, openid: app.globalData.openid, formids: formIds, type: 2 },
      function (res) {}
    )
  },
  collectFormIds: function (formId) {
    var formIds = app.globalData.globalFormIds
    if (!formIds) {
      formIds = []
    }
    var data = { formId: formId, expire: parseInt(new Date().getTime() / 1000) + 604800 }
    formIds.push(data)
    app.globalData.globalFormIds = formIds //保存推送码并赋值给变量
    wx.setStorageSync('globalFormIds', formIds)
  },

  formSubmit: function (e) {
    var formId = e.detail.formId
    this.collectFormIds(formId) //保存推送码
    //上传保存推送码
    this.saveFormIds()
  },

  //公司详情
  companyDetailTap: function (event) {
    var id = event.currentTarget.dataset.pid // 当前id
    wx.navigateTo({
      url: '../company-detail/company-detail?id=' + id,
    })
  },

  //发送简历
  isSendTap: function (e) {
    var that = this
    var formId = e.detail.formId
    if (
      app.globalData.openid != null &&
      !(
        that.data.isHaveResume == null ||
        that.data.isHaveResume == 'binded' ||
        that.data.isHaveResume == 'generated'
      )
    ) {
      var that = this
      if (that.data.isHaveResume === null) {
        that.setData({
          submitText: '请先完善您的个人资料',
          isHaveResume: false,
        })
      } else if(that.data.isHave <= 0){
        wx.showModal({
                  title: '请先上传简历',
                  content: '点击确认进行简历上传',
                  cancelText: '取消',
                  cancelColor: '#999',
                  confirmText: '确认',
                  confirmColor: '#4990E2',
                  success: function (res) {
                    if (res.confirm) {
                      wx.navigateTo({
                        url: '/pages/resume/resume',
                      })
                      return
                    } else if (res.cancel) {
                      return
                    }
                  },
                })
    
      } else {
        wx.showModal({
          title: '发送确认',
          content: '简历将发送至HR',
          cancelText: '取消',
          cancelColor: '#999',
          confirmText: '确认',
          confirmColor: '#4990E2',
          success: function (res) {
            if (res.confirm) {
              that.setData({
                submitText: '发送资料',
                isHaveResume: true,
              })
              app.loading()
              that.sendResumeFun(formId)
            } else if (res.cancel) {
            }
          },
        })
      }
    } else {
      if (
        that.data.isHaveResume == null ||
        that.data.isHaveResume == 'binded' ||
        that.data.isHaveResume == 'generated'
      ) {
        wx.showModal({
          title: '完善资料',
          content: '请完善您的资料',
          success: function (res) {
            if (res.confirm) {
              wx.reLaunch({
                url: '/pages/information/index',
                // url: '/pages/web-view/web-view',
                // url: '/pages/edit-resume-base/edit-resume-base?type=0',
              })
            } else if (res.cancel) {
            }
          },
        })
      } else {
        wx.showModal({
          title: '请先登录',
          content: '请微信授权登录,并完善您的资料',
          cancelText: '取消',
          cancelColor: '#999',
          confirmText: '确认',
          confirmColor: '#4990E2',
          success: function (res) {
            if (res.confirm) {
              app.loading()
              //that.sendResumeFun();
              wx.reLaunch({
                url: '/pages/user/index',
              })
            } else if (res.cancel) {
            }
          },
        })
      }
    }
  },
  moreposi: function () {
    wx.navigateBack({
      url: '/pages/home/home',
    })
  },
  //投递接口
  sendResumeFun: function (formId) {
    var that = this
    util.post(
      app.api.deliveryResume,
      {
        jobid: that.data.positionInfo.id,
        unionid: app.globalData.unionid,
        openid: app.globalData.openid,
        formid: formId,
      },
      function (data) {
        if (data.code == '200') {
          that.setData({
            height: '',
            successlabel: '投递成功，请耐心等待HR的反馈！',
          })
          var animation = wx.createAnimation({
            duration: 1000,
            timingFunction: 'ease',
          })

          that.setData({
            mode: false,
            animationData: animation.export(),
            //similarPosi: data.ret,
            submitText: '已申请',
            'yingpinBtn.disabled': true,
          })
          //缓存申请过的职位id
          try {
            var sendPosiArray = wx.getStorageSync('sendPosiArray')
            if (sendPosiArray) {
              // Do something with return value
              sendPosiArray.push(that.data.positionInfo.id)
              wx.setStorageSync('sendPosiArray', sendPosiArray)
            } else {
              var sendPosiArray = []
              sendPosiArray.push(that.data.positionInfo.id)
              wx.setStorageSync('sendPosiArray', sendPosiArray)
            }
          } catch (e) {
            // Do something when catch error
          }
        } else {
          app.alert(data.msg)
        }
        app.hideloading()
      }
    )
    //更多职位
    // util.post(
    //   app.api.similarPosi,
    //   { unionid: app.globalData.unionid, jobid: that.data.positionInfo.id },
    //   function (res) {
    //     that.setData({
    //       similarPosiInfo: res.data,
    //     })
    //   }
    // )
  },

  //职位详情
  positionDetailTap: function (event) {
    var id = event.currentTarget.dataset.id // 当前id
    // var position = null;
    // // 找出当时点击的那一项的详细信息
    // for (var d of this.data.similarPosi) {
    //   if (d.id == id) {
    //     position = d;
    //     break;
    //   }
    // }
    // if (!position) {
    //   console.log('系统出错');
    //   return;
    // }
    // 设置到全局变量中去，让下个页面可以访问
    // app.globalData.positionDetail = position;
    // 切换页面
    wx.navigateTo({
      url: '../position-detail/position-detail?pid=' + id,
    })
  },

  // 推荐职位
  recommandTap: function (event) {
    // 判断用户是否点击分享按钮
    if(event!=="toImged"){
      this.setData({
        click: true
      })
    }
    if(this.data.imgUrl && this.data.click){
      // 预览图片
      wx.previewImage(
        {
          urls: [this.data.imgUrl],
        },
        true
      )
      wx.hideLoading()
    }else if(this.data.click){
      // 显示loading
      wx.showLoading({
        title: '正在加载海报',
        mask: true,
      })
    }else{
      return
    }
    

    // var that=this;
    // if (app.globalData.openid != null &&!(that.data.isHaveResume == null || that.data.isHaveResume == 'binded' || that.data.isHaveResume == 'generated')) {
    //     var animation = wx.createAnimation({
    //       duration: 1000,
    //       timingFunction: 'ease',
    //     })
    //     wx.navigateTo({
    //       mode: false,
    //       animationData: animation.export(),
    //       url: '../position-recommand/position-recommand?position=' + JSON.stringify(this.data.positionInfo)
    //     });

    // }else{
    //   if (that.data.isHaveResume == null || that.data.isHaveResume == 'binded' || that.data.isHaveResume == 'generated') {
    //     wx.showModal({
    //       title: '完善资料',
    //       content: '请完善您的资料',
    //       success: function (res) {
    //         if (res.confirm) {
    //           wx.reLaunch({
    //             //url: '/pages/user/index',
    //             url: '/pages/web-view/web-view'
    //             // url: '/pages/edit-resume-base/edit-resume-base?type=0',
    //           });
    //         } else if (res.cancel) {

    //         }
    //       }
    //     })
    //   } else {
    //     wx.showModal({
    //       title: '请先登录',
    //       content: '请微信授权登录,并完善您的资料。',
    //       cancelText: '取消',
    //       cancelColor: '#999',
    //       confirmText: '确认',
    //       confirmColor: '#4990E2',
    //       success: function (res) {
    //         if (res.confirm) {
    //           app.loading();
    //           //that.sendResumeFun();
    //           wx.reLaunch({
    //             url: '/pages/user/index',
    //           })
    //         } else if (res.cancel) {

    //         }
    //       }
    //     })
    //   }
    // }
  },
  // 点击推荐生成canvas
  getCanvas: function(){
    var _this = this
    wx.getSystemInfo({
      success: function (res) {
        var num = (res.windowWidth / 375).toFixed(2)
        _this.setData({ rpx: num })
      },
    })
    var rpx = _this.data.rpx
    //给宽高赋值
    this.setData({ canvasHeight: rpx * 771 })
    this.setData({ canvasWidth: rpx * 545 })
    // 获取二维码图片
    let promiseScan = new Promise((reslove, reject) => {
      wx.getImageInfo({
        src: `${ _this.data.wechatQrcode }`,
        success(res) {
          console.log(res)
          reslove(res)
        },
        fail(err) {
          console.log(err, 'err')
          reject(err)
        },
      })
    })
    //获取背景图
    let promiseBGImage = new Promise((reslove, reject) => {
      wx.getImageInfo({
        src: 'https://tiaonali.com/position_background.png',
        success(res) {
          console.log(res)
          reslove(res)
        },
        fail(err) {
          console.log(err, 'err')
          reject(err)
        },
      })
    })
    // 获取公司头像
    let promiseComImg = new Promise((reslove, reject) => {
      wx.getImageInfo({
        src: `${_this.data.positionInfo.enterprise_logo}`,
        success(res) {
          console.log(res)
          reslove(res)
        },
        fail(err) {
          console.log(err, 'err')
          reslove(err)
        },
      })
    })
    // 获取hr头像
    let promiseHrImg = new Promise((reslove, reject) => {
      wx.getImageInfo({
        src: `${_this.data.positionInfo.hrHeadImgUrl}`,
        success(res) {
          console.log(res)
          reslove(res)
        },
        fail(err) {
          console.log(err, 'err')
          reslove(err)
        },
      })
    })
    Promise.all([promiseBGImage, promiseScan, promiseHrImg,promiseComImg]).then((res) => {
      console.log(res,"接口获取完成，开始绘制canvas")
      // //在自定义组件中使用canvas，获取wx.createCanvasContext第二个参数必须传入this，不然获取不到
      const ctx = wx.createCanvasContext('shareImg',this)
      //绘制背景图
      ctx.drawImage(
        res[0].path, //背景图
        0, //目标图片在画布中x坐标
        0, //目标图片在画布中y坐标
        750, //目标图片宽
        1334 //目标图片高
      )
      // 绘制一个白色矩形
      ctx.setFillStyle('#fff')
      ctx.fillRect(32, 850, 680, 400)
      //绘制二维码
      ctx.drawImage(
        res[1].path,
        500,
        1056,
        140,
        140
      )
      // // 绘制公司头像
      // ctx.drawImage(
      //   res[3].path,
      //   520,
      //   890,
      //   120,
      //   120
      // )
      // 绘制传瑞logo
      ctx.setFontSize(38)
      ctx.setFillStyle('#e9864d')
      ctx.fillText('MedTalent', 532, 66)
      // 绘制宣传语
      ctx.setFontSize(68)
      ctx.setFillStyle('#fff')
      ctx.fillText('Work Hard', 50, 416)
      ctx.fillText('Work Hard', 51, 415)
      ctx.fillText('Dream Big', 50, 512)
      ctx.fillText('Dream Big', 51, 511)
      // 绘制提示语
      ctx.rect(82,1160,300,36)
      ctx.setFillStyle('black')
      ctx.setFontSize(20)
      ctx.fillText('长按二维码，查看职位详情', 100, 1184)
      // 职位名
      ctx.setFontSize(22)
      ctx.setFillStyle('black')
      ctx.fillText(`高薪直聘 ${_this.data.positionInfo.name}`, 82, 1062)
      // 年薪
      ctx.setFontSize(32)
      ctx.setFillStyle('#efa986')
      ctx.fillText(
        `年薪：${
          _this.data.positionInfo.annualPayment > 0 ? _this.data.positionInfo.annualPayment : '面议'
        }`,
        82,
        1022
      )
      // 所在城市 || 发布日期
      let createDate = util.date_format_time(this.data.positionInfo.createDate)
      ctx.setFontSize(22)
      ctx.setFillStyle('#a6a6a6')
      ctx.fillText(`${_this.data.positionInfo.cityName} | ${ this.data.positionInfo.domainName } | ${createDate}`, 82, 1100)
      // positionInfo.annualPayment   公司地址：companyAddress   所在城市：cityName
      // 生成hr信息 hr  name:englishname 职位:roleName   头像连接：hrHeadImgUrl
      if (res[2].path) {
        ctx.drawImage(
          res[2].path,
          82,
          866,
          100,
          100
        )
      } else {
        ctx.drawImage(
          '../../images/hr.png',
          82,
          866,
          100,
          100
        )
      }
      ctx.setFillStyle('black')
      ctx.setFontSize(32)
      ctx.fillText(`${_this.data.positionInfo.englishname}`, 200, 906)
      // 公司名称
      ctx.setFontSize(28)
      ctx.setFillStyle('#a6a6a6')
      ctx.fillText(`${_this.data.positionInfo.companyName}`, 200, 956)
      // ctx.fillText(`${_this.data.positionInfo.roleName}`, 180, 570 )
      ctx.stroke()
      ctx.draw(false,()=>{
        console.log("生成图片开始")
        this.canvasToImg()
      })
    })
  },
  // 推荐职位生成图片
  canvasToImg: function () {
    var that = this
    wx.canvasToTempFilePath({
      // x: 0,
      // y: 0,
      // width: 750,
      // height: 1334,
      // destWidth: 750*4,
      // destHeight: 1334*4,
      canvasId: 'shareImg',
      success: function (res) {
        console.log(res.tempFilePath,'生成图片结束')
        /* 这里 就可以显示之前写的 预览区域了 把生成的图片url给image的src */
        that.setData({
          imgUrl: res.tempFilePath,
          imgHidden: true,
        },()=>{
          that.recommandTap('toImged')
        })
      },
      fail: function (res) {
        console.log(res)
      },
    })
  },
  //关闭成功提示
  closeTap: function () {
    this.setData({
      mode: true,
      height: '100%',
    })
  },
  //已申请职位提示
  myPosiTap: function () {
    wx.navigateTo({
      url: '/pages/my-position/my-position',
    })
  },
  //分享
  onShareAppMessage: function (res) {
    var that = this
    if (res.from === 'button') {
      // 来自页面内转发按钮
    }
    var title = that.data.positionInfo.companyName + ' 招聘 ' + that.data.positionInfo.name
    return {
      // title: title,
      // path: 'pages/position-detail/position-detail?pid=' + that.data.positionInfo.id,
      // data: that.data.positionInfo,
      imageUrl: this.data.imgUrl,
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      },
    }
  },
  onShareTimeline: function (res) {
    var title = that.data.positionInfo.companyName + ' 招聘 ' + that.data.positionInfo.name
    return {
      title: title,
      query: 'pid=' + that.data.positionInfo.id,
    }
  },
  onShow: function () {
    var that = this
    wx.getNetworkType({
      success: function (res) {
        // 返回网络类型, 有效值：
        // wifi/2g/3g/4g/unknown(Android下不常见的网络类型)/none(无网络)
        var networkType = res.networkType
        if (networkType == 'none') {
          that.setData({
            nonet: false,
            'yingpinBtn.disabled': true,
            submitdisabled: true,
          })
        }
      },
    })
  },
})
